﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.FeedingCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.FeedingCommandHandler
{
    public class AddFeedProductCommandHandler : IRequestHandler<AddFeedProductCommand, int>
    {
        IFeedingRepository fRep;
        IFeedProductRepository fpRep;
        IMapper mapper;
        ISqlSugarClient db;

        public AddFeedProductCommandHandler(IMapper mapper,
        ISqlSugarClient db, IFeedingRepository fRep,
        IFeedProductRepository fpRep)
        {
            this.mapper = mapper;
            this.db = db;
            this.fRep = fRep;
            this.fpRep = fpRep;
        }


        public async Task<int> Handle(AddFeedProductCommand request, CancellationToken cancellationToken)
        {
            // 开始事务
            db.Ado.BeginTran();

            try
            {
                //添加补料
                var feed = mapper.Map<Feeding>(request.AddDto);
                feed.FeNumber = Guid.NewGuid().ToString();
                var taskToAdd = await fRep.AddAsync(feed);


                //添加补料产品
                foreach (var item in request.AddDto.feedingProducts)
                {
                    FeedProduct detail = new FeedProduct
                    {
                        ProductId = item.ProductId,
                        FeNumber = feed.FeNumber,
                        Office_Id = item.Office_Id,
                        FePNum=item.FePNum,
                        ManpowerId=item.ManpowerId,
                        FePDeliveryDate =item.FePDeliveryDate,
                        User_Id = item.User_Id
                    };
                    await fpRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1;  // 返回最终的结果
            }
            catch (Exception)
            {
                // 回滚事务
                db.Ado.RollbackTran();
                throw;
            }
        }
    }
}
